<template>
  <div class="risk-scan-container">
    <!-- 顶部标题和风险点统计 -->
    <div class="header">
      <div class="title">
        <img src="@/assets/image/cf/img26.png" class="title-icon" />
        <h2>企业人力资源合规风险扫描仪</h2>
      </div>
      <div class="risk-count">
        共发现 <span class="highlight">{{ totalRiskCount }}</span> 个风险点
      </div>
      <div class="scan-status" v-if="loading">
        <el-icon color="#01509f"><Loading /></el-icon>
        正在扫描：{{ currentScanningModule }}
      </div>
    </div>

    <!-- 扫描进度条 -->
    <div class="progress-container" v-if="loading">
      <div class="progress-bar">
        <div 
          class="progress-fill" 
          :style="{ width: `${currentProgress}%` }"
        ></div>
      </div>
      <div class="progress-text">{{ currentProgress }}%</div>
    </div>

    <!-- 分类展示区 -->
    <div class="categories-container">
      <div 
        v-for="(modules, type) in categories" 
        :key="type" 
        class="category-card"
      >
        <div class="category-header">
          <img :src="getCategoryIcon(type)" class="category-icon" />
          <h3>{{ type }}</h3>
          <span class="risk-count">
            {{ getCategoryRiskCount(type) }}个风险点
          </span>
        </div>
        
        <div class="modules-grid">
          <div 
            v-for="module in modules" 
            :key="module.id" 
            class="module-item"
          >
            <div class="module-image-container">
              <img :src="module.img" class="module-image" />
              <!-- 风险数加载状态 -->
              <div class="risk-loading" v-if="!module.loaded">
                <el-icon class="loading-icon"><Loading /></el-icon>
              </div>
              <div 
                class="risk-tag" 
                v-else
                :class="module.count > 0 ? 'has-risk' : 'no-risk'"
              >
                {{ module.count > 0 ? `${module.count}个风险` : '无风险' }}
              </div>
            </div>
            <div class="module-name">{{ module.name }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 总分展示 -->
    <div class="total-score" v-if="!loading">
      <el-divider />
      <div class="score-display">
        <span>合规总分：</span>
        <el-tag :type="getScoreTagType(totalScore)" size="large">
          {{ totalScore }}/100
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
import { Loading } from '@element-plus/icons-vue';
import { useCompanyDataStore } from '@/store/companys';

interface RiskModule {
  id: number;
  type: string;
  name: string;
  img: string;
  x_img: string;
  count: number;
  progress: number;
  loaded: boolean; // 新增字段，标记是否已加载完成
}

export default defineComponent({
  name: 'RiskScanner',
  components: { Loading },
  setup() {
    const loading = ref(true);
    const currentProgress = ref(0);
    const currentScanningModule = ref('');
    const categories = ref<Record<string, RiskModule[]>>({});
    const totalScore = ref(0);
    const companyDataStore = useCompanyDataStore();

    // 计算总风险数
    const totalRiskCount = computed(() => {
      return Object.values(categories.value).reduce((total, modules) => {
        return total + modules.reduce((sum, module) => sum + module.count, 0);
      }, 0);
    });

    // 获取分类图标
    const getCategoryIcon = (type: string) => {
      const category = categories.value[type];
      return category && category.length > 0 ? category[0].x_img : '';
    };

    // 计算分类风险数
    const getCategoryRiskCount = (type: string) => {
      return categories.value[type]?.reduce((sum, module) => sum + module.count, 0) || 0;
    };

    // 分数标签类型
    const getScoreTagType = (score: number) => {
      return score >= 80 ? 'success' : 
             score >= 60 ? 'warning' : 'danger';
    };

    // 调用流式接口
    const loadRiskData = async () => {
      try {
        const companyId = companyDataStore.currentComanyInfo.id;
        const response = await fetch(
          `https://demo-api.niuyuwang.com/hr/detection/risk_check?company_id=${companyId}`,
          { headers: { Accept: 'text/event-stream' } }
        );

        if (!response.ok) throw new Error('接口请求失败');
        if (!response.body) throw new Error('不支持流式数据');

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const text = decoder.decode(value);
          const lines = text.split('\n').filter(line => line.trim() !== '');
          
          for (const line of lines) {
            if (line.startsWith('data:')) {
              const data = JSON.parse(line.substring(5).trim());
              
              if (data.status === 'starting') {
                categories.value = {};
                currentProgress.value = 0;
              } 
              else if (data.totale !== undefined) {
                totalScore.value = data.totale;
                loading.value = false;
              }
              else if (data.id !== undefined) {
                if (!categories.value[data.type]) {
                  categories.value[data.type] = [];
                }
                // 添加loaded字段，初始为false
                const moduleData = { ...data, loaded: false };
                categories.value[data.type].push(moduleData);
                currentProgress.value = data.progress;
                currentScanningModule.value = data.name;
                
                // 模拟延迟加载效果
                setTimeout(() => {
                  moduleData.loaded = true;
                }, 500 + Math.random() * 1000);
              }
            }
          }
        }
      } catch (err) {
        console.error('扫描失败:', err);
      }
    };

    // 初始化加载数据
    loadRiskData();

    return {
      loading,
      currentProgress,
      currentScanningModule,
      categories,
      totalScore,
      totalRiskCount,
      getCategoryIcon,
      getCategoryRiskCount,
      getScoreTagType
    };
  }
});
</script>

<style scoped>
.risk-scan-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'PingFang SC', sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.title-icon {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.title h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.risk-count {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.risk-count .highlight {
  color: #ff1200;
  font-weight: bold;
}

.scan-status {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #01509f;
  font-size: 14px;
}

.progress-container {
  margin: 30px 0;
  text-align: center;
}

.progress-bar {
  height: 10px;
  background: #f0f0f0;
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-fill {
  height: 100%;
  background: #01509f;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  color: #666;
}

.categories-container {
  margin-top: 20px;
}

.category-card {
  margin-bottom: 30px;
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.category-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.category-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.category-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  flex-grow: 1;
}

.category-header .risk-count {
  font-size: 14px;
  color: #666;
}

.modules-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 15px;
}

.module-item {
  background: #f9f9f9;
  border-radius: 6px;
  padding: 15px;
  transition: all 0.3s;
  text-align: center;
}

.module-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.module-image-container {
  position: relative;
  margin-bottom: 10px;
  min-height: 120px;
}

.module-image {
  width: 100%;
  height: 120px;
  object-fit: contain;
  border-radius: 4px;
}

/* 风险数加载状态样式 */
.risk-loading {
  position: absolute;
  bottom: 5px;
  right: 5px;
  width: 80px;
  height: 24px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-icon {
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.risk-tag {
  position: absolute;
  bottom: 5px;
  right: 5px;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  color: white;
}

.risk-tag.no-risk {
  background: #1fbe7d;
}

.risk-tag.has-risk {
  background: #ff1200;
}

.module-name {
  font-size: 14px;
  color: #333;
}

.total-score {
  margin-top: 30px;
  text-align: center;
}

.score-display {
  font-size: 18px;
  font-weight: bold;
}

.score-display span {
  margin-right: 10px;
}
</style>
